package com.quectel.business.common.util.sys;

import cn.hutool.core.convert.Convert;
import com.quectel.sys.module.sys.dto.SysCodeDto;
import com.quectel.sys.module.sys.service.SysCodeService;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.spring.SpringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 字典值帮助类
 * 在dubboservice中已经缓存过一次 controller频繁调用仍有性能问题所以抽出来进行再次缓存
 *
 * @author caolu
 * @email louis.cao@quectel.com
 */
@Component
public class SysCodeUtils {
    @DubboReference
    private SysCodeService sysCodeService;

    private static final String SYS_CODE_MARK = "SYS_CODE_MARK:";


    public static List<SysCodeDto> easyToGetByMark(String mark) {
        return SpringUtils.getBean(SysCodeUtils.class).getByMark(mark);
    }

    /**
     * 根据值获取标签名称
     *
     * @param mark
     * @param value
     * @return
     */
    public static String easyToGetName(String mark, String value) {
        List<SysCodeDto> sysCodeDtos = easyToGetByMark(mark);
        if (sysCodeDtos == null) {
            return null;
        }
        for (SysCodeDto sysCodeDto : sysCodeDtos) {
            if (Objects.equals(sysCodeDto.getValue(), value)) {
                return sysCodeDto.getName();
            }
        }
        return null;
    }

    /**
     * 根据值获取标签名称
     *
     * @param mark
     * @param name
     * @return
     */
    public static <T> T easyToGetValue(String mark, String name, Class<T> clazz) {
        List<SysCodeDto> sysCodeDtos = easyToGetByMark(mark);
        if (sysCodeDtos == null) {
            return null;
        }
        for (SysCodeDto sysCodeDto : sysCodeDtos) {
            if (Objects.equals(sysCodeDto.getName(), name)) {
                if (sysCodeDto.getValue() == null) {
                    return null;
                }
                return Convert.convert(clazz, sysCodeDto.getValue());
            }

        }
        return null;
    }

    private List<SysCodeDto> getByMark(String mark) {
        return CacheKit.cacheToRedis(
                () -> sysCodeService.queryListByMark(mark),
                SYS_CODE_MARK + mark,
                2 * 60
        );
    }


}
